package cn.stylefeng.guns.modular.agv.service.impl;

import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.modular.agv.entity.AgvStorageTask;
import cn.stylefeng.guns.modular.agv.entity.TuskAgvTask;
import cn.stylefeng.guns.modular.agv.mapper.TuskAgvTaskMapper;
import cn.stylefeng.guns.modular.agv.model.params.FeedbackTaskParam;
import cn.stylefeng.guns.modular.agv.model.params.FeedbackTaskRS;
import cn.stylefeng.guns.modular.agv.model.params.TuskAgvTaskParam;
import cn.stylefeng.guns.modular.agv.model.result.TuskAgvTaskResult;
import cn.stylefeng.guns.modular.agv.service.AgvStorageTaskService;
import cn.stylefeng.guns.modular.agv.service.TuskAgvTaskService;
import cn.stylefeng.guns.modular.agv.util.*;
import cn.stylefeng.guns.modular.hx.storage.entity.HxStorageOut;
import cn.stylefeng.guns.modular.hx.storage.model.params.HxStorageOutParam;
import cn.stylefeng.guns.modular.hx.storage.service.HxStorageOutService;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.aspectj.weaver.loadtime.ClassPreProcessorAgentAdapter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * TUSK小车任务表 服务实现类
 * </p>
 *
 * @author zhangzh
 * @since 2024-05-22
 */
@Service
public class TuskAgvTaskServiceImpl extends ServiceImpl<TuskAgvTaskMapper, TuskAgvTask> implements TuskAgvTaskService {

    @Value("${tusk.baseUrl}")
    private String tuskBaseUrl;

    @Value("${tusk.configId}")
    private String configId;

    @Autowired
    private AgvStorageTaskService agvStorageTaskService;

    @Autowired
    private HxStorageOutService hxStorageOutService;

    @Override
    public void add(TuskAgvTaskParam param) {
        TuskAgvTask entity = getEntity(param);
        this.save(entity);
    }

    @Override
    public ResponseData addTask(TuskAgvTaskParam param) {
        param.setConfigId(configId);
        param.setTaskId(CodeGenerateUtil.generate());
        //调用API接口
        TuskRsVo task = TustApiUtils.createTask(tuskBaseUrl, param);
        if (task == null) {
            return ResponseData.error("接口调用错误");
        } else if (task.getCode() != 200) {
            return ResponseData.error(task.getMsg());
        } else {

            TuskAgvTask entity = getEntity(param);
            this.save(entity);
        }
        return ResponseData.success();
    }

    @Override
    public void delete(TuskAgvTaskParam param) {
        this.removeById(getKey(param));
    }

    @Override
    public void update(TuskAgvTaskParam param) {
        TuskAgvTask oldEntity = getOldEntity(param);
        TuskAgvTask newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public TuskAgvTaskResult findBySpec(TuskAgvTaskParam param) {
        return null;
    }

    @Override
    public List<TuskAgvTaskResult> findListBySpec(TuskAgvTaskParam param) {
        return null;
    }

    @Override
    public LayuiPageInfo findPageBySpec(TuskAgvTaskParam param, String condition) {
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param, condition);
        return LayuiPageFactory.createPageInfo(page);
    }

    private Serializable getKey(TuskAgvTaskParam param) {
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private TuskAgvTask getOldEntity(TuskAgvTaskParam param) {
        return this.getById(getKey(param));
    }

    private TuskAgvTask getEntity(TuskAgvTaskParam param) {
        TuskAgvTask entity = new TuskAgvTask();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

    @Override
    public FeedbackTaskRS feedbackTask(FeedbackTaskParam feedbackTaskParam) {
        FeedbackTaskRS feedbackTaskRS = new FeedbackTaskRS();
        feedbackTaskRS.setCode(200);
        feedbackTaskRS.setMsg("success");
        if (StringUtils.isBlank(feedbackTaskParam.getTaskId())) {
            feedbackTaskRS.setCode(500);
            feedbackTaskRS.setMsg("[任务编号]不能为空！！！");
            return feedbackTaskRS;
        }
        if (StringUtils.isBlank(feedbackTaskParam.getTaskStatus())) {
            feedbackTaskRS.setCode(500);
            feedbackTaskRS.setMsg("[任务状态]不能为空！！！");
            return feedbackTaskRS;
        }
        if ("getComplete".equals(feedbackTaskParam.getTaskStatus())) {
            //取货
            this.baseMapper.updateByTaskId(TuskAgvTaskParam.builder()
                    .taskId(feedbackTaskParam.getTaskId())
                    .stat("10")
                    .getCompleteTime(new Date())
                    .build());
        } else if ("putComplete".equals(feedbackTaskParam.getTaskStatus())) {
            //放货
            this.baseMapper.updateByTaskId(TuskAgvTaskParam.builder()
                    .taskId(feedbackTaskParam.getTaskId())
                    .stat("20")
                    .putCompleteTime(new Date())
                    .build());
        } else if ("cancel".equals(feedbackTaskParam.getTaskStatus())) {
            //取消
            this.baseMapper.updateByTaskId(TuskAgvTaskParam.builder()
                    .taskId(feedbackTaskParam.getTaskId())
                    .stat("90")
                    .cancelTime(new Date())
                    .build());
        } else if ("forceComplete".equals(feedbackTaskParam.getTaskStatus())) {
            //强制完成任务
            this.baseMapper.updateByTaskId(TuskAgvTaskParam.builder()
                    .taskId(feedbackTaskParam.getTaskId())
                    .stat("30")
                    .forceCompleteTime(new Date())
                    .build());
        }
        return feedbackTaskRS;
    }

    @Override
    public FeedbackTaskRS agvStorageFeedbackTask(FeedbackTaskParam feedbackTaskParam) {
        FeedbackTaskRS feedbackTaskRS = new FeedbackTaskRS();
        feedbackTaskRS.setCode(200);
        feedbackTaskRS.setMsg("success");
        if (StringUtils.isBlank(feedbackTaskParam.getTaskId())) {
            feedbackTaskRS.setCode(500);
            feedbackTaskRS.setMsg("[任务编号]不能为空！！！");
            return feedbackTaskRS;
        }
        if (StringUtils.isBlank(feedbackTaskParam.getTaskStatus())) {
            feedbackTaskRS.setCode(500);
            feedbackTaskRS.setMsg("[任务状态]不能为空！！！");
            return feedbackTaskRS;
        }
        if ("getComplete".equals(feedbackTaskParam.getTaskStatus())) {
            String agvNo = feedbackTaskParam.getAgvNo();
            if(ToolUtil.isEmpty(agvNo) && ToolUtil.isNotEmpty(feedbackTaskParam.getDeviceId())){
                agvNo = feedbackTaskParam.getDeviceId();
            }
            //取货
            this.agvStorageTaskService.lambdaUpdate()
                    .eq(AgvStorageTask::getTaskNo,feedbackTaskParam.getTaskId())
                    .set(AgvStorageTask::getAgvNo,agvNo)
                    .update();
            //获取拣货单号
            AgvStorageTask one = this.agvStorageTaskService.lambdaQuery().eq(AgvStorageTask::getTaskNo, feedbackTaskParam.getTaskId()).one();
            HxStorageOut hxStorageOut = this.hxStorageOutService.lambdaQuery().eq(HxStorageOut::getStorageNumber, one.getStorageNumber()).one();
            if(hxStorageOut != null){
                //修改拣选人
                this.hxStorageOutService.lambdaUpdate()
                        .eq(HxStorageOut::getId,hxStorageOut.getId())
                        .set(HxStorageOut::getAgvNo,agvNo)
                        .update();
            }
        }
        return feedbackTaskRS;
    }

    @Override
    public StorageRsVo getMapStorage() {
        return TustApiUtils.getMapStorage(tuskBaseUrl);
    }

    @Override
    public StorageRsVo getMapStorageByRoadway(String roadway) {
        return TustApiUtils.getMapStorageByRoadway(tuskBaseUrl,roadway);
    }

    @Override
    public FeedbackTaskRS setPriority(PriorityParamVo priority) {
        return TustApiUtils.setPriority(tuskBaseUrl, priority);
    }

    @Override
    public FeedbackTaskRS clear(String areaName) {
        TustApiUtils.unlock(tuskBaseUrl,areaName);
        return TustApiUtils.clear(tuskBaseUrl,areaName);
    }

    @Override
    public void clearAll() {
        StorageRsVo mapStorage = TustApiUtils.getMapStorage(tuskBaseUrl);
        if(mapStorage != null){
            TustApiUtils.unlock(tuskBaseUrl,"");
            for(StorageDataVo obj : mapStorage.getData()){
                FeedbackTaskRS clear = TustApiUtils.clear(tuskBaseUrl, obj.getAreaName());
                //System.out.println(clear.getMsg());
            }
        }
    }
}
